#include "Thread.hpp"
#include "LockGuard.hpp"
using namespace yss;

int g_ticket = 5000;

class DataThread
{
public:
    DataThread(int& ticket, const string& name, pthread_mutex_t& mutex)
        :_ticket(ticket), _name(name), _total(0), _mutex(mutex)
    {}

    ~DataThread()
    {}

    string _name;
    int& _ticket;//全局的
    int _total;
    pthread_mutex_t& _mutex;//共用一把锁
};
// pthrear_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// void route(DataThread* td)
// {
//     while(true)
//     {
//         pthread_mutex_lock(&td->_mutex);//加锁
//         //抢票
//         if(td->_ticket > 0)
//         {
//             usleep(1000);
//             printf("%s is run..., ticket: %d\n", td->_name.c_str(), td->_ticket);
//             td->_ticket--;
//             pthread_mutex_unlock(&td->_mutex);//解锁
//             td->_total++;
//         }
//         else 
//         {
//             pthread_mutex_unlock(&td->_mutex);//解锁
//             break;
//         }
//     }
// }
void route(DataThread* td)
{
    while(true)
    {
        LockGuard guard(&td->_mutex);//临时对象，构造即加锁，析构即解锁
        //抢票
        if(td->_ticket > 0)
        {
            usleep(1000);
            printf("%s is run..., ticket: %d\n", td->_name.c_str(), td->_ticket);
            td->_ticket--;
            td->_total++;
        }
        else 
        {
            break;
        }
    }
}
const int num = 4;
int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, nullptr);//初始化锁

    vector<Thread<DataThread*>> threads;
    vector<DataThread*> datas;
    for(int i = 0; i < num; i++)
    {
        string name = "thread-" + to_string(i+1);
        DataThread* td = new DataThread(g_ticket, name, mutex);
        threads.emplace_back(route, td, name);
        datas.emplace_back(td);
    }
    //创建
    for(auto& thread:threads)
    {
        thread.Satrt();
    }
    //等待
    for(auto& thread:threads)
    {
        thread.Join();
    }
    //打印每个线程获取的票数
    for(auto& data:datas)
    {
        cout << data->_name << " total is: " << data->_total << endl;
    }
    pthread_mutex_destroy(&mutex);//释放锁
    return 0;
}